package com.skyz.wrap.http;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.skyz.base.application.BaseApplication;
import com.skyz.base.manager.ActivityManager;
import com.skyz.base.util.NetWorkUtil;
import com.skyz.wrap.entity.result.CommAppJsonResult;
import com.skyz.base.http.HttpRequestCallback;
import com.skyz.wrap.manager.RouteManager;
import com.skyz.wrap.manager.TokenManager;

public abstract class CommonAppHttpRequestCallback<DATA> extends HttpRequestCallback<CommAppJsonResult<DATA>> {

    private final String TAG = getClass().getSimpleName();

    protected CommonAppHttpRequestCallback(boolean showLoading) {
        super(showLoading);
    }

    @Override
    protected void onHttpRequestSuccess(CommAppJsonResult<DATA> data) {
        if (data.getCode() != 200) {
            if (data.getCode() == 401) {
                ToastUtils.show("登录失效，请重新登录");
                Application application = BaseApplication.getApplication();
                TokenManager.getInstance().setToken(application, null);
                Activity activity = ActivityManager.getInstance().currentActivity();
                if (activity == null) {
                    return;
                }
                ActivityManager.getInstance().finishAllActivity();
                RouteManager.getInstance().showActivity(activity, "LoginActivity");
                return;
            }
            onCommonAppHttpRequestFail(data.getMessage());
            return;
        }
        Gson gson = new Gson();
        Log.e("http", gson.toJson(data.getData()));
        onCommonAppHttpRequestSuccess(data.getData());
    }

    @Override
    protected void onHttpRequestFail(Throwable e) {
        Activity activity = ActivityManager.getInstance().currentActivity();
        if (activity != null) {
            if (!NetWorkUtil.isNetSystemUsable(activity)) {
                onCommonAppHttpRequestNetWorkUsable();
                return;
            }
        }
        onCommonAppHttpRequestFail(e.getMessage());
    }

    protected abstract void onCommonAppHttpRequestSuccess(DATA data);

    protected void onCommonAppHttpRequestFail(String msg) {
        ToastUtils.show(msg);
    }

    protected void onCommonAppHttpRequestFail(CommAppJsonResult<DATA> data) {

    }

    protected void onCommonAppHttpRequestNetWorkUsable() {
        onCommonAppHttpRequestFail("No Network");
    }
}
